"""
更新库存
"""
import os
import sys
import django
import math

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.extend([BASE_DIR, ])
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finance_c2c.settings")
django.setup()
from apps.supply_order.models import Goods
from apps.supply_order.models import AreaWareHouse
from apps.supply_order.models import Inventory
from apps.supply_order.womai_api import WoMaiApi


class UpdateInventory(WoMaiApi):
    # 更新库存
    def create_inventory(self, skuids_str):
        area_ware_house = AreaWareHouse.objects.all()
        for area in area_ware_house:
            content = self.get_inventory(
                skuids_str, area.p_code
            )
            inventory = content.get("Inventory")
            for i in inventory:
                num = i.get("inventory")
                skuid = i.get('skuid')
                goods_obj = Goods.objects.get(goodsid=skuid)
                in_obj, created = Inventory.objects.get_or_create(
                    goods=goods_obj,
                    ware_house=area
                )
                in_obj.num = num
                in_obj.save()
                # if num and int(num) > 0:
                #     goods_obj.can_sale = True
                # else:
                #     goods_obj.can_sale = False
                # goods_obj.save()

    def for_range(self):
        queryset = Goods.objects.filter(company__sign="womaiwang")
        skuids = queryset.values_list('goodsid', flat=True)
        sku_count = skuids.count()
        r = math.ceil(sku_count / 100.0)
        for i in range(r):
            start_index = i * 100
            end_index = (i + 1) * 100 - 1
            skuids = queryset.values_list('goodsid', flat=True)[start_index:end_index]
            skuids = map(lambda x: str(x), skuids)
            skuids_str = ",".join(skuids)
            self.create_inventory(skuids_str)
        # 更新商品
        goods_id_list = Inventory.objects.filter(num=0).distinct().values_list("goods_id", flat=True)
        goods_queryset = Goods.objects.filter(id__in=goods_id_list)
        goods_queryset.update(can_sale=False)
        can_sale_goods_queryset = Goods.objects.exclude(id__in=goods_id_list)
        can_sale_goods_queryset.update(can_sale=True)


if __name__ == '__main__':
    updateInventory = UpdateInventory()
    updateInventory.for_range()
